<script setup>
import { ref, computed } from 'vue'
import { NModal, NCard, NButton, NIcon, NImage, NInput, NTooltip, NForm, NFormItem } from 'naive-ui'
import { Robot, Sitemap, Upload } from '@vicons/tabler'
import { Close } from '@vicons/ionicons5'

const showModal = ref(false)
const selectedType = ref('agent')
const appName = ref('')
const appDescription = ref('')
const currentIcon = ref('https://picsum.photos/id/1/100/100')
const iconHistory = ref([
  'https://picsum.photos/id/3/100/100',
  'https://picsum.photos/id/2/100/100',
  'https://picsum.photos/id/4/100/100',
  'https://picsum.photos/id/5/100/100'
])
const canGenerateIcon = ref(true)

const formRef = ref(null)
const formValue = ref({
  type: 'agent',
  name: '',
  description: '',
  icon: ''
})

const rules = {
  name: {
    required: true,
    message: '请输入应用名称',
    trigger: 'blur'
  },
  description: {
    required: true,
    message: '请输入应用描述',
    trigger: 'blur'
  }
}

const selectType = (type) => {
  if (type !== 'workflow') {
    selectedType.value = type
    formValue.value.type = type
  }
}

const uploadIcon = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = (e) => {
    const file = e.target.files[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        currentIcon.value = e.target.result
        iconHistory.value.unshift(e.target.result)
        if (iconHistory.value.length > 4) {
          iconHistory.value.pop()
        }
        formValue.value.icon = e.target.result
      }
      reader.readAsDataURL(file)
    }
  }
  input.click()
}

const generateDescription = () => {
  appDescription.value = '这是一个由AI生成的应用描述。它展示了应用的主要功能和特点。'
  formValue.value.description = appDescription.value
}

const generateIcon = () => {
  if (canGenerateIcon.value) {
    const newIcon = `https://placekitten.com/${Math.floor(Math.random() * 10) + 40}/${Math.floor(Math.random() * 10) + 40}`
    currentIcon.value = newIcon
    iconHistory.value.unshift(newIcon)
    if (iconHistory.value.length > 4) {
      iconHistory.value.pop()
    }
    formValue.value.icon = newIcon
  }
}

const selectHistoryIcon = (icon) => {
  currentIcon.value = icon
  formValue.value.icon = icon
}

const closeModal = () => {
  showModal.value = false
}

const createApplication = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      console.log('Creating application:', formValue.value)
      closeModal()
    } else {
      console.log('Validation failed:', errors)
    }
  })
}

const isFormValid = computed(() => {
  return (
    formValue.value.type &&
    formValue.value.name.trim() !== '' &&
    formValue.value.description.trim() !== ''
  )
})

const openModal = () => {
  showModal.value = true
}

defineExpose({ openModal })
</script>

<template>
  <n-modal v-model:show="showModal" @close="closeModal">
    <n-card
      class="modal-card rounded-2xl"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
      <template #header>
        <div class="modal-header">
          <h2 class="modal-title">创建空白应用</h2>
          <div class="cursor-pointer" @click="closeModal">
            <n-icon size="20" class="color-gray-500">
              <close />
            </n-icon>
          </div>
        </div>
      </template>
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        label-width="auto"
        require-mark-placement="right-hanging"
      >
        <n-form-item label="应用类型" path="type">
          <div class="app-type-selector w-full">
            <div
              class="app-type-option"
              :class="{ selected: selectedType === 'agent' }"
              @click="selectType('agent')"
            >
              <n-icon size="25" class="app-type-icon" color="#444CE7"><robot /></n-icon>
              <span class="app-type-label">Agent</span>
            </div>
            <div
              class="app-type-option disabled"
              :class="{ selected: selectedType === 'workflow' }"
            >
              <n-icon size="25" class="app-type-icon" color="#F79009"><sitemap /></n-icon>
              <span class="app-type-label">工作流</span>
            </div>
          </div>
        </n-form-item>

        <n-form-item label="名称" path="name">
          <n-input v-model:value="formValue.name" placeholder="给你的应用起个名字" />
        </n-form-item>

        <n-form-item label="描述" path="description">
          <n-input
            v-model:value="formValue.description"
            type="textarea"
            placeholder="输入应用的描述"
            :autosize="{
              minRows: 3,
              maxRows: 5
            }"
          />
        </n-form-item>

        <n-form-item label="图标" path="icon">
          <div class="icon-upload__wrapper">
            <div class="icon-preview" @click="uploadIcon">
              <n-image :src="currentIcon" alt="App Icon" class="current-icon" />
              <div class="icon-upload-overlay">
                <n-icon size="30" color="#fff"><Upload /></n-icon>
              </div>
            </div>
            <div class="icon-actions">
              <div class="ai-generate-history">
                <n-tooltip trigger="hover" placement="top">
                  <template #trigger>
                    <div
                      class="ai-generate-avatar"
                      @click="generateIcon"
                      :class="{ disabled: !canGenerateIcon }"
                    >
                      <n-icon size="20"><Robot /></n-icon>
                      <span>Generate</span>
                    </div>
                  </template>
                  Ai基于你的描述生成图标.
                </n-tooltip>

                <img
                  v-for="(icon, index) in iconHistory"
                  :key="index"
                  :src="icon"
                  :width="80"
                  :height="80"
                  class="history-icon"
                  @click="selectHistoryIcon(icon)"
                />
              </div>
            </div>
          </div>
        </n-form-item>
      </n-form>

      <template #footer>
        <div class="modal-footer">
          <n-button @click="closeModal">取消</n-button>
          <n-button type="primary" @click="createApplication" :disabled="!isFormValid">
            创建
          </n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<style lang="scss" scoped>
$primary-color: #155aef;

.modal {
  &-card {
    width: 700px;
    max-width: 90%;
  }

  &-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &-title {
    font-size: 1.125rem;
    font-weight: bold;
  }

  &-content {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  &-footer {
    display: flex;
    justify-content: flex-end;
    gap: 1rem;
  }
}
.app-type-option {
  &.disabled {
    opacity: 0.5;
    cursor: not-allowed;
    &:hover {
      border: 1px solid #fff;
    }
  }
}
.app-type {
  &-selector {
    display: flex;
    gap: 1rem;
  }

  &-option {
    height: 5rem;
    flex: 1;
    border: 1px solid #fff;
    border-radius: 0.5rem;
    cursor: pointer;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-image: url('@/assets/grid-bg-chat.svg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.1);

    &:hover {
      border: 1px solid #e5e7eb;
    }

    &.selected {
      border: $primary-color solid 1px;
    }
  }

  &-icon {
    margin-bottom: 5px;
  }

  &-label {
    font-size: 14px;
  }
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.icon-upload__wrapper {
  display: flex;
  align-items: flex-end;
  gap: 1rem;
}

.icon-preview {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 0.5rem;
  overflow: hidden;
  cursor: pointer;

  &:hover .icon-upload-overlay {
    opacity: 1;
  }
}

.icon-upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.icon-actions {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.ai-generate-history {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.history-icon {
  cursor: pointer;
  border-radius: 0.25rem;
  transition: transform 0.2s;

  &:hover {
    transform: scale(1.1);
  }
}

.ai-generate-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 0.2rem;
  padding: 0.25rem 0.5rem;
  width: 80px;
  height: 80px;
  background-color: #f3f3f3;
  border-radius: 0.5rem;
  cursor: pointer;

  &:hover {
    color: $primary-color;
    background: rgba($primary-color, 0.1);
    box-shadow:
      0 4px 6px -1px rgba(0, 0, 0, 0.1),
      0 2px 4px -1px rgba(0, 0, 0, 0.06);
    border: 1px solid $primary-color;
  }

  &.disabled {
    opacity: 0.5;
    cursor: not-allowed;
    &:hover {
      color: inherit;
      background: none;
      box-shadow: none;
    }
  }
}
</style>
